package org.gongliang.kit.file;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.gongliang.common.KConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.google.common.collect.Lists;


/**
 * 文件上传工具类
 * 
 * @author 龚亮
 * @version 1.0
 */
public class FileKit {

	private static final Logger logger = LoggerFactory.getLogger(FileKit.class);

	public static long ONE_KB = 1024;
	public static long ONE_MB = ONE_KB * 1024;
	public static long ONE_GB = ONE_MB * 1024;
	public static long ONE_TB = ONE_GB * 1024;
	public static long ONE_PB = ONE_TB * 1024;

	/**
	 * 多文件上传
	 */
	public static List<UploadFile> multiUpload(HttpServletRequest request) {
		return multiUpload(request, null);
	}

	/**
	 * 单文件上传
	 */
	public static UploadFile upload(HttpServletRequest request) {
		List<UploadFile> listFiles = multiUpload(request, null);
		if (listFiles.size() > 0) {
			return listFiles.get(0);
		}
		return null;
	}

	public static UploadFile upload(HttpServletRequest request, String fileDir) {
		List<UploadFile> listFiles = multiUpload(request, fileDir);
		if (listFiles.size() > 0) {
			return listFiles.get(0);
		}
		return null;
	}
	/**
	 * 多文件上传
	 */
	public static List<UploadFile> multiUpload(HttpServletRequest request, String fileDir) {
		List<UploadFile> files = Lists.newArrayList();
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) (request);
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					String myFileName = file.getOriginalFilename();
					if (myFileName.trim() != "") {
						UploadFile uploadFile = new UploadFile(file, fileDir);
						files.add(uploadFile);
						String path = KConfig.me().getFileUploadPath() + uploadFile.getPath();
						File localFile = new File(path);
						try {
							if (!localFile.exists() && !localFile.isDirectory()) {
								localFile.mkdirs();
							}
							file.transferTo(new File(path));
						} catch (Exception e) {
							logger.debug("创建文件异常:" + path);
						}
					}
				}
			}
		}
		return files;
	}

}
